package com.itheima.controller;

import com.itheima.Permission;
import com.itheima.Role;
import com.itheima.service.IPermissionService;
import com.itheima.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;

    /**
     * 查询所有角色
     *
     * @return
     */
    @RequestMapping("/findAll.do")
    public ModelAndView findAll() {

        ModelAndView mv = new ModelAndView();

        List<Role> roleList = roleService.findAll();

        mv.addObject("roleList", roleList);

        mv.setViewName("role-list");
        return mv;
    }

    /**
     * 添加角色
     *
     * @param role
     * @return
     */
    @RequestMapping("/save.do")
    public String save(Role role) {

        roleService.save(role);
        return "redirect:findAll.do";
    }

    @RequestMapping("/findOtherPermissionByRoleId.do")
    public ModelAndView findOtherPermissionByRoleId(@RequestParam(name = "id") String roleId) {

        ModelAndView mv = new ModelAndView();
        Role role = roleService.findById(roleId);
        List<Permission> permissionList = permissionService.findOtherPermission(roleId);
        mv.addObject("role",role);
        mv.addObject("permissionList",permissionList);
        mv.setViewName("role-permission-add");
        return mv;
    }

    @RequestMapping("/addPermissionToRole.do")
    public String addPermissionToRole(String roleId,String[] permissionIds){

        roleService.addPermissionToRole(roleId,permissionIds);
        return "redirect:findAll.do";
    }
}
